<?php
require_once('./includes/headers.inc.php');

if(isset($_SESSION['user'])) {
    require_once('./top.php');
}

global $admin_users;

$error = FALSE;

$newsMgr = new News();
if($_POST) {
    $post = array(
        'date' => $_POST['date'],
        'description' => $_POST['description'],
    );
    if($newsMgr->add($post)) {
        $error = $msgMgr->get('add-news-success');
    } else {
        $error = $msgMgr->get('add-news-error');
    }
    header('Location: /news.php');
    exit();
}

$news = $newsMgr->getAll();
$news_list = array();
if(isset($_GET['rss'])) {
    foreach($news as $row) {
        $news_list[] =
            '<item>' .
            '<title>' . $row['date'] . '</title>' . "\n" .
            '<link>http://vertigo.merijn.nu/news.php</link>' . "\n" .
            '<description>' . $row['description'] . '</description>' . "\n" .
            '</item>' . "\n";
    }
} else {
    foreach($news as $row) {
        $news_list[] = '<li><b>' . $row['date'] . '</b>: ' . $row['description'] . '</li>';
    }
}

if(isset($_SESSION['user']['id']) && in_array($_SESSION['user']['id'], $admin_users)) {
    $replaces = array(
        'news'              => implode("\n", $news_list),
        'admin_form'        => '<b>Add item:</b><br><textarea name="description"></textarea><br>' .
                            '<input type="text" name="date" value="' . date('Y-m-d') . '">' .
                            '<input type="submit">',
        'error'             => $msgMgr->formatMsg($error),
    );
} else {
    $replaces = array(
        'news'              => implode("\n", $news_list),
        'admin_form'        => '',
        'error'             => $msgMgr->formatMsg($error),
    );
}
$lang = array(
    'header_news'       => $langMgr->get('header_news'),
    'text_rss'          => $langMgr->get('text_rss'),
);
if(isset($_GET['rss'])) {
    header('Content-Type: text/xml');
    $templateMgr->loadContent(basename(__FILE__, '.php') . 'rss', $replaces);
    $templateMgr->loadFooter(FALSE);
} else {
    $templateMgr->loadContent(basename(__FILE__, '.php'), array_merge($replaces, $lang));
}
?>
